﻿using System;
using System.Net;
using System.Windows;
using Microsoft.Phone.Controls;
using Alien.NetWork;
using DBHelper.DB;
using DBHelper;
using System.Linq;

namespace PhoneUI
{
    public partial class MainPage : PhoneApplicationPage
    {
        private PhoneData db;
        private SettingCollection settingcol = new SettingCollection();

        // 建構函式
        public MainPage()
        {
            InitializeComponent();

            //注册接收事件
            SocketHelper.OnReceiveMessage += new MessageHandler(SocketHelper_OnReceiveMessage);
            //注册连接套字失败事件
            SocketHelper.OnSocketError += new ErrorHandler(SocketHelper_OnSocketError);

            db = new PhoneData(PhoneData.connectString);
            IpBox.Text = (from SettingTable setting in db.Setting
                          where setting.SettingName == "IpAddress"
                          select new
                          {
                              setting.SettingValue
                          }
                          ).DefaultIfEmpty().First().SettingValue;

            PortBox.Text = (from SettingTable setting in db.Setting
                            where setting.SettingName == "Port"
                            select
                                new
                                {
                                    setting.SettingValue
                                }).DefaultIfEmpty().First().SettingValue;
        }

        void SocketHelper_OnSocketError(System.Net.Sockets.SocketException e)
        {
            Dispatcher.BeginInvoke(() =>
                {
                    ConnectBlock.Text = "连接失败:" + e.SocketErrorCode.ToString();
                    MessageBox.Show(e.Message);
                });
        }


        //验证IP格式
        private bool VeriIp(string ip)
        {
            bool result = false;
            IPAddress ipa;
            if (IPAddress.TryParse(ip, out ipa))
            {
                result = true;
            }
            else
            {
                MessageBox.Show("请输入正确的IP地址！");
            }
            return result;
        }

        //验证端口格式
        private bool VeriPort(string port, out int Num)
        {
            bool result = false;
            int output;
            if (int.TryParse(port, out output))
            {
                result=true;
            }
            else
            {
                MessageBox.Show("输入的端口格式不正确");
            }
            Num = output;
            return result;
        }

        //开始连接
        private void Connect()
        {
            int port;
            if (VeriIp(IpBox.Text.Trim()) && VeriPort(PortBox.Text.Trim(), out port))
            {
                ConnectBlock.Text = "连接中...";
                ConnectPanel.Visibility = Visibility.Visible;
                
                SocketHelper.Create(IpBox.Text.Trim(), port);
                SocketHelper.Send("Connected");
            }
            else
            {
                return;
            }
        }

        void SocketHelper_OnReceiveMessage(MessageEventArgs e)
        {
            if (e.Message == "Success")
            {
                Dispatcher.BeginInvoke(() =>
                    {
                        ConnectPanel.Visibility = Visibility.Collapsed;
                        this.NavigationService.Navigate(new Uri("/Pages/Control.xaml",UriKind.Relative));
                        return;
                    });
            }
            else
            {
                Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show(e.Message);
                        ConnectPanel.Visibility = Visibility.Collapsed;
                    });
            }
        }

        #region 按键事件

        private void ConnectBtn_Click(object sender, RoutedEventArgs e)
        {
            Connect();
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/Pages/Setting.xaml", UriKind.Relative));
        }

        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            Connect();
        }

        #endregion
    }
}